package com.monkeyboy.util;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Arrays;

/**
 * 认证的方式
 *
 * @Author Gavin
 * @date 2021.01.10 16:54
 */
public class MongoDBAuthUtil {
    private static MongoClient client = null;

    static {
        if (client == null) {
            //创建一个封装用户的认证信息
            MongoCredential credential = MongoCredential.createCredential("test", "test", "123456".toCharArray());
            //封装Mongodb的地址和端口信息
            ServerAddress serverAddress = new ServerAddress("192.168.1.55", 27017);
            //创建连接对象
            client = new MongoClient(serverAddress, Arrays.asList(credential));
        }
    }

    //获取mongodb数据库
    public static MongoDatabase getDatabase(String dbName) {
        return client.getDatabase("test");
    }

    //获取mongodb中的集合
    public static MongoCollection<Document> getCollection(String dbname, String collName) {
        MongoDatabase database = getDatabase(dbname);
        return database.getCollection(collName);
    }

    //创建集合
    public static void createCollection(String dbName, String collName) {
        MongoDatabase database = getDatabase(dbName);
        database.createCollection(collName);
    }

    //删除集合
    public static void dropCollection(MongoCollection<Document> coll) {
        coll.drop();
    }

    public static void main(String[] args) {

        createCollection("test","java_coll");
    }
}
